/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.ventas;

import dp1.titandevelop.titano.bean.Estado;
import dp1.titandevelop.titano.bean.FiltroDV;
import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.DetalleDamanda;
import dp1.titandevelop.titano.persistent.DetalleDocumentoVenta;
import dp1.titandevelop.titano.persistent.DetalleSolicitudVenta;
import dp1.titandevelop.titano.persistent.DocumentoVenta;
import dp1.titandevelop.titano.persistent.Parametro;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.persistent.SolicitudVenta;
import dp1.titandevelop.titano.persistent.TipoDocumento;
import dp1.titandevelop.titano.persistent.Turno;
import dp1.titandevelop.titano.service.AlmacenService;
import dp1.titandevelop.titano.service.DocumentoVentaService;
import dp1.titandevelop.titano.service.SolicitudVentaService;
import dp1.titandevelop.titano.service.ValidacionService;
import dp1.titandevelop.titano.view.BusquedaProductoCantidad;
import dp1.titandevelop.titano.view.MensajeCantidadProducto;
import dp1.titandevelop.titano.view.MensajeError;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.access.DataContext;

/**
 *
 * @author Heli
 */
public class ModulosT_VEN_AVDocDetalle extends javax.swing.JInternalFrame {
    
    public ModulosT_VEN_AV ventanaNuevo = null;
    public List<TipoDocumento> tipoD;
    public Parametro parametro;
    
    List <DetalleDocumentoVenta> dDv=new ArrayList<DetalleDocumentoVenta>();
    public int estadoNuevo = 0;    
    public int idDistribuidor;
    public int idNotaCredito=0;
    public int tipo;
    public int idSV;
    public int idSD;
    public float impuestos;
    public FiltroDV busqueda;
    public float subtotalMasIgv;
    public int tipoDocumento;
    public int idDocumento;
    public String ruc;
    
    
    private void actualizarSuma(){
        Float valor;
       
        
        if(!txtDescuento.getText().equalsIgnoreCase(""))
        valor=sumaItem()+Float.valueOf(txtIgv.getText())-impuestos-(Float.valueOf(txtDescuento.getText()));
        else
            valor=sumaItem()+Float.valueOf(txtIgv.getText())-impuestos;
        txtTotal.setText(String.valueOf(valor));
        
        
    }
    
    
    
    //public DocumentoVenta doc=
    
    public void habilitaBotones(){
        this.btnBuscarDistribuidor.setEnabled(true);
        this.txtDistribuidor.setEditable(true);
        
        
    }
    
    public void habilitaBotonesList(){
        //this.btnNuevo.setEnabled(false);
        if(this.idSV==0)
        this.btnEliminarA.setEnabled(true);
        else 
        this.btnEliminarA.setEnabled(false);
        
    }
    
    public void inhabilitaBotonesList(){
       // this.btnNuevo.setEnabled(true);
        this.btnEliminarA.setEnabled(false);
        
        
    }
     private void inhabilitaBotonesBoleta(){
        this.tipoDocumento=2;
        this.btnBuscarDistribuidor.setEnabled(false);
        this.txtDistribuidor.setEnabled(false);
        this.idDistribuidor=0;
        this.idSV=0;
        this.txtIgv.setEnabled(false);
        this.txtContacto.setEnabled(true);
        this.txtDireccion.setEnabled(true);
        this.txtDNI.setEnabled(true);
        this.txtPedido.setEnabled(false);
        this.btnBuscarSolicitud.setEnabled(false);
        DocumentoVentaService servicex=new DocumentoVentaService();
        //this.txtNumDoc.setText(servicex.numeroBoleta());
        
        this.txtDescuento.setEnabled(false);
        this.labeContacto.setText("Contacto");
        this.labelDNI.setVisible(true);
        this.txtDNI.setVisible(true);
        
    }
    private void inhabilitaBotonesFactura(){
        this.tipoDocumento=1;
        this.btnBuscarDistribuidor.setEnabled(true);
        this.txtDistribuidor.setEditable(true);
        
        this.btnBuscarSolicitud.setEnabled(true);
        this.txtPedido.setEnabled(true);
        
        this.idDistribuidor=0;
        
        this.txtIgv.setEnabled(true);
        this.txtDistribuidor.setEnabled(true);
        this.txtContacto.setEnabled(false);
        this.txtDireccion.setEnabled(false);
        this.txtDNI.setEnabled(false);
        DocumentoVentaService servicex=new DocumentoVentaService();
        //this.txtNumDoc.setText(servicex.numeroFactura());
        
        this.txtDescuento.setEnabled(true);
        this.labeContacto.setText("Razón Social");
        this.txtRUC.setText("RUC:");
        this.txtDNI.setVisible(false);
        this.labelDNI.setVisible(false);
        
    }
    
    private void resetearTodo(){
            idSV=0;
        this.txtPedido.setText("");
        this.txtFecha.setDate(null);
        this.txtDistribuidor.setText("");
        this.txtContacto.setText("");
            
        
    }
    
    
    private void inhabilitaBotonesSolicitud(){
        this.btnBuscarDistribuidor.setEnabled(false);
        this.txtDistribuidor.setEditable(false);
        
    }
    
    private void inhabilitarInicio(){
          this.txtDistribuidor.setEditable(false);
          this.txtPedido.setEditable(false);
          this.txtTotal.setEditable(false);
          this.txtDescuento.setEditable(false);
          //this.tableResultados.setEnabled(false);
      
    }
    
    
    
    private void inhabilitarTodo(){
          this.btnNuevo.setVisible(false);
          this.btnEliminarA.setVisible(false);
          this.btnBuscarDistribuidor.setVisible(false);
          this.btnBuscarSolicitud.setVisible(false);
          this.btnGuardar.setVisible(false);
          this.txtFecha.setEditable(false);
          this.txtDistribuidor.setEditable(false);
          this.txtPedido.setEditable(false);
          this.txtFecha.setEditable(false);
          this.txtDescuento.setEditable(false);
          this.txtContacto.setEditable(false);
          this.txtDNI.setEditable(false);
          this.txtDireccion.setEditable(false);
          this.txtTotal.setEditable(false);
          //this.tableResultados.setEnabled(false);
      
    }
    
     private float sumaItem(){
    float valor=0,sbt=0;
    for(int i=0;i<dDv.size();i++){
    sbt=dDv.get(i).getCantidad()*(dDv.get(i).getToProducto().getCosto()+dDv.get(i).getToProducto().getBeneficio());
    valor+=sbt;
    dDv.get(i).setMonto(sbt);
    dDv.get(i).setEstado(1);
    }
    return valor;
    
    }
public   float roundTwoDecimals(float d) { 
Integer v=Math.round(d*100);
Float v2=Float.valueOf((float)v/(float)100);
return v2;
}  
    
    public void incrustarDSVaDDV(List<DetalleSolicitudVenta>dsv){
        this.dDv.clear();
        ObjectContext context = DataContext.createDataContext();
        for(int i=0;i<dsv.size();i++){
            DetalleDocumentoVenta ddv=(DetalleDocumentoVenta)context.newObject(DetalleDocumentoVenta.class);
            Producto p=(Producto)context.newObject(Producto.class);
             System.out.println(i+" producto: "+p.getDescripcion());
            p.setIdproducto(dsv.get(i).getToProducto().getIdproducto());
            p.setDescripcion(dsv.get(i).getToProducto().getDescripcion());
            p.setCosto(dsv.get(i).getToProducto().getCosto());
            p.setBeneficio(dsv.get(i).getToProducto().getBeneficio());
            p.setUm(dsv.get(i).getToProducto().getUm());
            ddv.setCantidad(dsv.get(i).getCantidad());
            ddv.setToProducto(p);
            ddv.setMonto((dsv.get(i).getToProducto().getCosto()+dsv.get(i).getToProducto().getBeneficio())*dsv.get(i).getCantidad());
            dDv.add(ddv);
            
        }
     this.actualizarProductosList();
    }
    
    public ModulosT_VEN_AVDocDetalle() {
        initComponents(); 
        inhabilitaBotonesList();
        ValidacionService validacionService = new ValidacionService();
        validacionService.SLetras(this.txtContacto);
        validacionService.SNumeros(this.txtDNI);
        validacionService.SAlfanumerico(this.txtDireccion);
        validacionService.NoEscribe(this.txtFecha);
        //validacionService.SNumeros(this.txtDescuento);
        //validacionService.esFechaVacia(txtFecha);
        
        this.btnImprimir.setVisible(false);
        this.txtDescuento.setText("0");
        
        DocumentoVentaService service=new DocumentoVentaService();
        this.tipoD=service.buscarTipoDocumento();
        this.parametro=service.parametros();
        
        this.actualizarAllList();
        this.inhabilitarInicio();
    }
    
    public ModulosT_VEN_AVDocDetalle(DocumentoVenta d, FiltroDV dv,int tipo) {
        initComponents(); 
        inhabilitaBotonesList();
        this.txtDescuento.setText("0");
        
        DocumentoVentaService service=new DocumentoVentaService();
        SolicitudVentaService service2=new SolicitudVentaService();
        this.tipoD=service.buscarTipoDocumento();
        this.parametro=service.parametros();
    
        this.idDocumento=d.getIddocumento();
        this.ruc=d.getToSolicitudVenta().getToDistribuidor().getRuc();
        this.txtRuc.setText(this.ruc);
    System.out.println("RUC "+this.ruc);
        
        this.txtFecha.setDate(d.getFechafacturacion());
        this.txtDistribuidor.setText(d.getToSolicitudVenta().getToDistribuidor().getRazonsocial());
        this.txtContacto.setText(d.getContacto());
        String numS=service2.numeroSolicitudView(d.getToSolicitudVenta().getIdsolicitudventa());
        if(numS=="")
            this.txtPedido.setText("Sin Solicitud");
        else
            this.txtPedido.setText("Solicitud #"+service2.numeroSolicitudView(d.getToSolicitudVenta().getIdsolicitudventa()));
        
        this.txtDNI.setText(d.getDni());
        this.txtDireccion.setText(d.getDireccion());
        this.txtSubTotal.setText(String.valueOf(d.getMontototal()));
        this.txtDescuento.setText(String.valueOf(d.getDescuento()));
        this.txtIgv.setText(String.valueOf(d.getIgv()));
        this.txtTotal.setText(String.valueOf(d.getTotal()));
        this.tipoDocumento=d.getToTipoDocumento().getIdtipodocumento();
    
        if(this.tipoDocumento==1){
        System.out.println(this.idDocumento);
            this.txtNumDoc.setText(service.numeroFacturaView(this.idDocumento));
           this.txtTipoDocumento.setText("Factura");
           inhabilitaBotonesFactura();
           
       }else{
           this.txtNumDoc.setText(service.numeroBoletaView(this.idDocumento));
           this.txtTipoDocumento.setText("Boleta");
           inhabilitaBotonesBoleta();
       }
       
      
        this.dDv=service.buscarFiltrado2(d.getIddocumento());
        this.busqueda=dv;
        this.idDistribuidor=d.getToSolicitudVenta().getToDistribuidor().getIddistribuidor();
        this.actualizarProductosList();
        
        this.tipo=tipo;
        this.idSD=d.getIddocumento();
        //this.actualizarSuma();
        if(this.tipo==2){
        this.inhabilitarTodo();
        this.btnImprimir.setVisible(true);
        ///this.actualizarAllList();
        }
    }
    
    
    
    
    
    
    
    
    
    
Thread actualizarproducto = null;
    private void actualizarProductosList(){
        if( actualizarproducto!=null && actualizarproducto.isAlive() ){
            actualizarproducto.interrupt();
        }
        actualizarproducto = new Thread( new Runnable() {
            @Override
            public void run() {
                RefreshTable();
                ModeloTabla modelo= new ModeloTabla();
                tableResultados.setModel(modelo);
               // txtSubTotal.setText(String.valueOf(roundTwoDecimals(sumaItem())));
                //txtTotal.setText(String.valueOf(roundTwoDecimals(sumaItem()+Float.valueOf(txtIgv.getText())-impuestos)));
            }
        });
        actualizarproducto.start();
    }
    
Thread actualizarAll = null;
    private void actualizarAllList(){
        if( actualizarAll!=null && actualizarAll.isAlive() ){
            actualizarAll.interrupt();
        }
        actualizarAll = new Thread( new Runnable() {
            @Override
            public void run() {
                while(true){
                Float valor=roundTwoDecimals(sumaItem());
                
                txtSubTotal.setText(String.valueOf(valor));
                if(tipoDocumento==2){
                   
                    txtIgv.setText(String.valueOf(roundTwoDecimals(Float.valueOf(txtSubTotal.getText())*parametro.getIgv())));
                
                }else
                    txtIgv.setText("0");
                subtotalMasIgv=roundTwoDecimals(Float.valueOf(txtSubTotal.getText())+Float.valueOf(txtIgv.getText()));
                actualizarSuma();
                System.out.println("IGV: "+txtIgv.getText());
                //txtTotal.setText(String.valueOf(sumaItem()+Float.valueOf(txtIgv.getText())-impuestos));
                
                }
            }
        });
        actualizarAll.start();
    }
    
    
    //metodo para refrescar la tabla
    public void RefreshTable() {
        
        AbstractTableModel aux = (AbstractTableModel)tableResultados.getModel();
        aux.fireTableDataChanged();
    }
    
    class ModeloTabla extends AbstractTableModel {  
        //Atributos de los datos de la tabla
        private String [] titles = {"Producto", "Cantidad","Unidad","Precio Unitario (S/.)","Importe (S/.)"};
        //private List<DataTabla> datos;
        //private Object [][]datos;
        
        public int getRowCount() {
            return dDv.size();//tipos.size(); // cuantos registros (filas)
        }      
        
        public int getColumnCount() {
            return 5; // cuantas columnas
        }          
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }                
       
        public Object getValueAt(int rowIndex, int columnIndex) {
            Object res=null;
            DetalleDocumentoVenta d = dDv.get(rowIndex);
            //boolean b = datos.get(rowIndex).seleccionado;//tipos.get(rowIndex);
            switch(columnIndex){
                case 0: res = d.getToProducto().getDescripcion(); break;
                case 1: res = d.getCantidad(); break;
                case 2: res = d.getToProducto().getUm(); break;
                case 3: res = d.getToProducto().getCosto()+d.getToProducto().getBeneficio(); break;
                case 4: res = String.valueOf(roundTwoDecimals(d.getMonto())); break;
                //case 2: res = b;
            }
            return res;
        } 
        //Ultima celda editable para selección
        @Override
        public boolean isCellEditable(int row, int col) {
            boolean res=false;
            switch (col) {
                case 0:break;
                case 1:break;
               // case 2:res=true;
            }
            return res;
        }
        //para obtener las clases de cada celda y asi mostrar estas correctamente
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
//        @Override
//        public void setValueAt(Object value, int row, int col) {
//            datos.get(row).seleccionado = (Boolean)value;
//        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        txtDistribuidor = new javax.swing.JTextField();
        btnBuscarDistribuidor = new javax.swing.JButton();
        txtDNI = new javax.swing.JTextField();
        labelDNI = new javax.swing.JLabel();
        labeContacto = new javax.swing.JLabel();
        txtContacto = new javax.swing.JTextField();
        labelDNI2 = new javax.swing.JLabel();
        txtDireccion = new javax.swing.JTextField();
        txtRUC = new java.awt.Label();
        txtRuc = new java.awt.Label();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableResultados = new javax.swing.JTable();
        btnNuevo = new javax.swing.JButton();
        btnEliminarA = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        txtSubTotal = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        txtDescuento = new javax.swing.JTextField();
        txtIgv = new javax.swing.JTextField();
        txtTotal = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        txtPedido = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        btnBuscarSolicitud = new javax.swing.JButton();
        txtTipoDocumento = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtFecha = new org.jdesktop.swingx.JXDatePicker();
        txtNumDoc = new javax.swing.JLabel();
        btnImprimir = new javax.swing.JButton();

        setResizable(true);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Documento de Venta"));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos de Documento"));

        jLabel7.setText("Cliente/Distribuidor");

        btnBuscarDistribuidor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar2.png"))); // NOI18N
        btnBuscarDistribuidor.setToolTipText("");
        btnBuscarDistribuidor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarDistribuidorActionPerformed(evt);
            }
        });

        labelDNI.setText("DNI");

        labeContacto.setText("Contacto");

        labelDNI2.setText("Dirección");

        txtRUC.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
        txtRUC.setText("RUC:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(jLabel7))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(labeContacto))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(labelDNI2)))
                .addGap(15, 15, 15)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtDistribuidor, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtContacto, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(btnBuscarDistribuidor)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtRUC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(2, 2, 2)
                        .addComponent(txtRuc, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(labelDNI)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtDNI, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel7)
                        .addComponent(txtDistribuidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btnBuscarDistribuidor))
                    .addComponent(txtRuc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtRUC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtContacto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labeContacto)
                    .addComponent(labelDNI)
                    .addComponent(txtDNI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelDNI2, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Detalle de Documento de Venta"));

        jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        tableResultados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Producto", "Cantidad", "Unidad", "Precio Unitario (S/.)", "Importe (S/.)"
            }
        ));
        tableResultados.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableResultadosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tableResultados);
        tableResultados.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        btnNuevo.setToolTipText("Nuevo");
        btnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoActionPerformed(evt);
            }
        });

        btnEliminarA.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminarA.setToolTipText("Eliminar");
        btnEliminarA.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarAActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 562, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnNuevo)
                    .addComponent(btnEliminarA))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(btnNuevo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEliminarA)))
                .addGap(8, 8, 8))
        );

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnCancelar.setToolTipText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        txtSubTotal.setEditable(false);

        jLabel12.setText("Nota de Crédito (S/)");

        txtDescuento.setEditable(false);

        txtIgv.setEditable(false);

        jLabel13.setText("Sub-total (S/.)");

        jLabel14.setText("IGV (S/.)");

        jLabel15.setText("Total (S/.)");

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanel5Layout.createSequentialGroup()
                            .addGap(10, 10, 10)
                            .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(jPanel5Layout.createSequentialGroup()
                                    .addComponent(jLabel14)
                                    .addGap(67, 67, 67))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel5Layout.createSequentialGroup()
                                    .addComponent(jLabel13)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                            .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtSubTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(txtIgv, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jLabel15)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel12)
                        .addGap(8, 8, 8)
                        .addComponent(txtDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(txtSubTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29))
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jLabel13)
                        .addGap(10, 10, 10)
                        .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel14)
                            .addComponent(txtIgv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(10, 10, 10)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(txtDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel15))
                .addContainerGap(81, Short.MAX_VALUE))
        );

        jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos"));

        jLabel8.setText("Pedido");

        btnBuscarSolicitud.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar2.png"))); // NOI18N
        btnBuscarSolicitud.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarSolicitudActionPerformed(evt);
            }
        });

        txtTipoDocumento.setText("Factura");

        jLabel5.setText("Fecha");

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel6Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtTipoDocumento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel6Layout.createSequentialGroup()
                                .addComponent(txtPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnBuscarSolicitud))
                            .addComponent(txtNumDoc, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel6Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtNumDoc, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtTipoDocumento))
                .addGap(10, 10, 10)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtPedido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnBuscarSolicitud)
                    .addComponent(jLabel8))
                .addGap(10, 10, 10)
                .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10))
        );

        btnImprimir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/imprimir.png"))); // NOI18N
        btnImprimir.setToolTipText("Imprimir");
        btnImprimir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImprimirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(8, 8, 8)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnImprimir)
                        .addGap(1, 1, 1)
                        .addComponent(btnGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(1, 1, 1)
                        .addComponent(btnCancelar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(8, 8, 8))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(2, 2, 2)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnGuardar)
                    .addComponent(btnCancelar)
                    .addComponent(btnImprimir))
                .addGap(8, 8, 8))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
        final int i=0;
        final busquedaProductoCantidad seleccionarProductoForm0 =new busquedaProductoCantidad(null, true);
        seleccionarProductoForm0.setLocationRelativeTo(this);
        seleccionarProductoForm0.addWindowListener(new WindowAdapter() {
                        @Override
			public void windowClosed(WindowEvent e) {
                            if(seleccionarProductoForm0.idProducto!=null && seleccionarProductoForm0.estoy=="productoCantidad"){
                            if(seleccionarProductoForm0.idProducto>0){
                                int aumentar=1;
                                DetalleDocumentoVenta d=new DetalleDocumentoVenta();
                                d.setCantidad(seleccionarProductoForm0.cantidad);
                                ObjectContext context = DataContext.createDataContext();
                                Producto p=(Producto)context.newObject(Producto.class);
                                p.setIdproducto(seleccionarProductoForm0.idProducto);
                                p.setDescripcion(seleccionarProductoForm0.producto);
                                p.setCosto(seleccionarProductoForm0.costo);
                                d.setToProducto(p);
                                seleccionarProductoForm0.idProducto=0;
                                
                                
                                //d.getToProducto().setDescripcion();
                            
                                for(int i=0;i<dDv.size();i++){
                                    if(dDv.get(i).getToProducto().getDescripcion().equals(p.getDescripcion())){
                                        dDv.get(i).setCantidad(d.getCantidad());
                                        aumentar=0;
                                    }
                                }
                                
                                if(aumentar==1) dDv.add(d);
                           actualizarProductosList();
                           //System.out.println(seleccionarProductoForm.producto);
                            }
                            }
                            //this;
			}
		});
        seleccionarProductoForm0.setVisible(true);   
    }//GEN-LAST:event_btnNuevoActionPerformed

    private void tableResultadosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableResultadosMouseClicked
        if(evt.getClickCount()==1){
            this.habilitaBotonesList();
        }
        
    }//GEN-LAST:event_tableResultadosMouseClicked

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        Mensajes mensajes = new Mensajes();
        ValidacionService validacionService = new ValidacionService();
        if ((validacionService.esFechaVacia(txtFecha)) || (validacionService.esVacio(txtSubTotal)) || (validacionService.esVacio(txtTotal))  || (Float.valueOf(txtTotal.getText())==0) || dDv.size()==0) {
            JOptionPane.showInternalMessageDialog(this.getRootPane(), mensajes.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);

        } else {
        
            AlmacenService serviceA =new AlmacenService();
            Integer estado=1;
            //aca debo pasar el id del producto, devuelve una lista: o capacidad total del almcen y el stock es el 1
            for(int i=0;i<dDv.size();i++){
            List<Integer> capacidad_StockTotalProducto = serviceA.capacidad_StockTotalProducto(dDv.get(i).getToProducto().getIdproducto());
            Integer cantMax=capacidad_StockTotalProducto.get(1);
                if(cantMax<this.dDv.get(i).getCantidad()){
                    estado=0;
                    System.out.println("Acabo de salir");
                    MensajeCantidadProducto dialog = new MensajeCantidadProducto(new javax.swing.JFrame(), true,cantMax);
                          dialog.setLocationRelativeTo(null);
                          dialog.setVisible(true);
                    break;
                }
            }
      if(estado==1){        
        try {
            //Usamos el atributo creado para modificar el registro seleccionado
            
            Estado state= new Estado();
            Date fechaActual=new Date();
            ObjectContext context = DataContext.createDataContext();
            DocumentoVenta dv=(DocumentoVenta)context.newObject(DocumentoVenta.class);
            SolicitudVenta sv=(SolicitudVenta)context.newObject(SolicitudVenta.class);
            TipoDocumento td=(TipoDocumento)context.newObject(TipoDocumento.class);
            sv.setIdsolicitudventa(idSV);
            td.setIdtipodocumento(Integer.valueOf(this.tipo));
            
            dv.setToSolicitudVenta(sv);
            dv.setToTipoDocumento(td);
            
            if(!this.txtContacto.getText().isEmpty())            
                dv.setContacto(this.txtContacto.getText());
            else
                dv.setContacto("");
            
            if(!this.txtDNI.getText().isEmpty())            
                dv.setDni(this.txtDNI.getText());
            else
                dv.setDni("");
            
            if(!this.txtDireccion.getText().isEmpty())            
                dv.setDireccion(this.txtDireccion.getText());
            else
                dv.setDireccion("");
            
            dv.setFechaemision(fechaActual);
            dv.setMontototal(Float.valueOf(this.txtSubTotal.getText()));
            dv.setFechafacturacion(this.txtFecha.getDate());
            
            
            if(!this.txtIgv.getText().isEmpty())            
                dv.setIgv(Float.valueOf(this.txtIgv.getText()));
            else
                dv.setIgv(Float.valueOf("0"));
            //impuestos
            
            dv.setRetencion(Float.valueOf("0"));
            dv.setPercepcion(Float.valueOf("0"));
            dv.setDetraccion(Float.valueOf("0"));
                        
            if(!this.txtDescuento.getText().isEmpty())            
                dv.setDescuento(Float.valueOf(this.txtDescuento.getText()));
            else
                dv.setDescuento(Float.valueOf("0"));
            
            if(!this.txtTotal.getText().isEmpty())            
                dv.setTotal(Float.valueOf(this.txtTotal.getText()));
            else
                dv.setTotal(Float.valueOf("0"));
            
            
            dv.setEstado(state.getPendiente());
            
            System.out.println("Llegue hasta aki");
            DocumentoVentaService service= new DocumentoVentaService(); 
            service.insertar(dv,dDv,this.idNotaCredito);
           
            JOptionPane.showInternalMessageDialog(this.getRootPane(), "La operación se realizó de forma exitosa!","Mensaje",JOptionPane.INFORMATION_MESSAGE);

        } catch(Exception e) {
            //e.printStackTrace();
            MensajeError dialog = new MensajeError(new javax.swing.JFrame(), true);
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
        }
      
        ventanaNuevo = new ModulosT_VEN_AV();            
            this.getParent().add(ventanaNuevo);
            Dimension desktopSize = this.getParent().getSize();
            Dimension jInternalFrameSize = ventanaNuevo.getSize();
            ventanaNuevo.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                    (desktopSize.height - jInternalFrameSize.height)/4 );
            ventanaNuevo.show();
        this.dispose();
        }
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        ventanaNuevo = new ModulosT_VEN_AV();            
            this.getParent().add(ventanaNuevo);
            Dimension desktopSize = this.getParent().getSize();
            Dimension jInternalFrameSize = ventanaNuevo.getSize();
            ventanaNuevo.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                    (desktopSize.height - jInternalFrameSize.height)/4 );
            ventanaNuevo.show();
        this.dispose();
        
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnBuscarDistribuidorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarDistribuidorActionPerformed
        final BusquedaDistribuidor seleccionarProductoForm =new BusquedaDistribuidor(null, true);
        seleccionarProductoForm.setLocationRelativeTo(this);
        seleccionarProductoForm.addWindowListener(new WindowAdapter() {
                        @Override
			public void windowClosed(WindowEvent e) {
                            if(seleccionarProductoForm.idDistribuidor!=null && seleccionarProductoForm.estoy=="distribuidor"){
                                if(seleccionarProductoForm.idDistribuidor>0){
                                idDistribuidor=seleccionarProductoForm.idDistribuidor;
                                txtDistribuidor.setText(seleccionarProductoForm.distribuidor);
                                txtContacto.setText(seleccionarProductoForm.distribuidor);
                               //con esto paro el evento
                                seleccionarProductoForm.idDistribuidor=0;
                              }
                            }
                            //this;
			}
		});
        seleccionarProductoForm.setVisible(true);
    }//GEN-LAST:event_btnBuscarDistribuidorActionPerformed

    private void btnBuscarSolicitudActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarSolicitudActionPerformed
       final BusquedaSolicitudPedido seleccionarProductoForm1 =new BusquedaSolicitudPedido(null, false);
        seleccionarProductoForm1.setLocationRelativeTo(this);
        seleccionarProductoForm1.addWindowListener(new WindowAdapter() {
                        @Override
			public void windowClosed(WindowEvent e) {
                            if(seleccionarProductoForm1.idSolicitudVenta!=null && seleccionarProductoForm1.estoy=="solicitudVenta"){
                                if(seleccionarProductoForm1.idSolicitudVenta>0){
                                idDistribuidor=seleccionarProductoForm1.idDistribuidor;
                                idSV=seleccionarProductoForm1.idSolicitudVenta;
                                txtDistribuidor.setText(seleccionarProductoForm1.distribuidor);
                                txtContacto.setText(seleccionarProductoForm1.distribuidor);
                                
                                txtPedido.setText("Solicitud #"+seleccionarProductoForm1.idSolicitudVenta);
                                 SolicitudVentaService service = new SolicitudVentaService();
                               List<DetalleSolicitudVenta> dsv= new ArrayList<DetalleSolicitudVenta>();
                               System.out.println("Sorprendentement ingrese aqui");
                               dsv=service.buscarFiltrado2(idSV);
                               dDv.clear();         
                               btnNuevo.setEnabled(false);
                               btnEliminarA.setEnabled(false);
                               incrustarDSVaDDV(dsv);
                               dsv.clear();
                               btnBuscarDistribuidor.setVisible(false);
                               
                               //con esto paro el evento
                                seleccionarProductoForm1.idSolicitudVenta=0;
                                    }
                                }
                            //this;
			}
		});
        seleccionarProductoForm1.setVisible(true);
    }//GEN-LAST:event_btnBuscarSolicitudActionPerformed

    private void btnEliminarAActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarAActionPerformed
        int confirmar = JOptionPane.showInternalConfirmDialog(this.getRootPane(),"¿Está seguro que desea eliminar el registro?","Aviso!",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);

        if (JOptionPane.OK_OPTION == confirmar)
        {//Obtengo el objeto seleccionado
            DocumentoVentaService serv = new DocumentoVentaService();
            DetalleDocumentoVenta dist = dDv.get(this.tableResultados.getSelectedRow());
            this.dDv.remove(this.tableResultados.getSelectedRow());
            
        }

        this.RefreshTable();
        this.inhabilitaBotonesList();
    }//GEN-LAST:event_btnEliminarAActionPerformed

    private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
        try {
            Calendar calendario = GregorianCalendar.getInstance();
                
                SimpleDateFormat formatoDeFecha = new SimpleDateFormat("dd/MM/yyyy");
                String fecha2=formatoDeFecha.format(this.txtFecha.getDate());
                
                String nombreArchivo = "/tmp/factura.pdf";
            FileDialog fd = new FileDialog(new JFrame(), "Guardar", FileDialog.SAVE);
            fd.setDirectory(".");
            fd.setFile("*.pdf");
            fd.setVisible(true);
            nombreArchivo = fd.getDirectory() + fd.getFile();
            if(fd.getFile()!=null){
                    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
            printFactura print=new printFactura(this.dDv,this.idDocumento,this.txtContacto.getText(), fecha2, this.ruc,this.tipoDocumento,Float.valueOf(this.txtSubTotal.getText()),
           Float.valueOf(this.txtIgv.getText()),Float.valueOf(this.txtDescuento.getText()),Float.valueOf(this.txtTotal.getText()),nombreArchivo,this.txtDireccion.getText(),this.txtNumDoc.getText());
            this.setCursor(Cursor.getDefaultCursor());
            JOptionPane.showInternalMessageDialog(this.getRootPane(),"La factura a sido generada satisfactoriamente","Mensaje",JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (Exception ex) {
            Logger.getLogger(ModulosT_VEN_AVDocDetalle.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }//GEN-LAST:event_btnImprimirActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscarDistribuidor;
    private javax.swing.JButton btnBuscarSolicitud;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEliminarA;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnImprimir;
    private javax.swing.JButton btnNuevo;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labeContacto;
    private javax.swing.JLabel labelDNI;
    private javax.swing.JLabel labelDNI2;
    public javax.swing.JTable tableResultados;
    private javax.swing.JTextField txtContacto;
    private javax.swing.JTextField txtDNI;
    private javax.swing.JTextField txtDescuento;
    private javax.swing.JTextField txtDireccion;
    private javax.swing.JTextField txtDistribuidor;
    private org.jdesktop.swingx.JXDatePicker txtFecha;
    private javax.swing.JTextField txtIgv;
    private javax.swing.JLabel txtNumDoc;
    private javax.swing.JTextField txtPedido;
    private java.awt.Label txtRUC;
    private java.awt.Label txtRuc;
    private javax.swing.JTextField txtSubTotal;
    private javax.swing.JLabel txtTipoDocumento;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables
}
